import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd';
import { CustomService } from 'src/app/service/custom.service';

@Component({
  selector: 'app-password',
  templateUrl: './password.component.html',
  styleUrls: ['./password.component.less']
})
export class PasswordComponent implements OnInit {

  validateForm!: FormGroup;

  submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.status == "VALID") {
      var data = this.validateForm.value;
      this.customService.password(data).subscribe(result => {
        this.validateForm.reset();
        for (const key in this.validateForm.controls) {
          this.validateForm.controls[key].markAsPristine();
          this.validateForm.controls[key].updateValueAndValidity();
        }
        this.modalService.success({
          nzTitle: '信息提示',
          nzContent: '密码修改成功,下次登录请使用新密码!'
        });
      });
    }
  }

  confirmValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { error: true, required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  };

  constructor(
    private fb: FormBuilder,
    private modalService: NzModalService,
    private customService: CustomService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      oldPassword: [null, [Validators.required, Validators.pattern(/^[0-9a-zA-Z]{4,20}$/)]],
      password: [null, [Validators.required, Validators.pattern(/^[0-9a-zA-Z]{4,20}$/)]],
      confrimPassword: [null, [this.confirmValidator]],
    });
  }

}
